package com.alm.token.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.BuyHMioAddData;
import com.alm.token.ui.data.bean.HMioMapData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.BuyHMioView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.EthWalletUtil;
import com.yzq.zxinglibrary.android.CaptureActivity;

import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

//import com.yzq.zxinglibrary.android.CaptureActivity;

public class HMioMapActivity extends BaseActivity implements BuyHMioView<HMioMapData> {

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_hmio_money)
    TextView tvHmioMoney;
    @BindView(R.id.img_bizhongicon)
    ImageView imgBizhongicon;
    @BindView(R.id.edt_inputadress)
    EditText edtInputadress;
    @BindView(R.id.img_saoma)
    ImageView imgSaoma;
    @BindView(R.id.tv_copyadress)
    ImageView tvCopyadress;
    @BindView(R.id.tv_hmiomid)
    TextView tvHmiomid;
    @BindView(R.id.tv_copymid)
    ImageView tvCopymid;
    @BindView(R.id.ly_midbody)
    LinearLayout lyMidbody;
    @BindView(R.id.tv_hmiomapcommit)
    TextView tvHmiomapcommit;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    private HMioMapData.DataBeanX hMioMapDataData;
    private HMioMapData.DataBeanX.DataBean hMioMapDataDataData;
    private static final int QRCODE_SCANNER_REQUEST = 1100, VERIFY_REQUEST = 1101;

    @Override
    protected MyPreenter initPreenter() {
        return preenter = new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_hmiomap;
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.hmiomap_hint_title));
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(false);
                loadData();
            }
        });
        //设置EditText的显示方式为多行文本输入
        edtInputadress.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        //文本显示的位置在EditText的最上方
        edtInputadress.setGravity(Gravity.CENTER_VERTICAL);
        edtInputadress.setText("");
        //改变默认的单行模式
        edtInputadress.setSingleLine(false);
        //水平滚动设置为False
        edtInputadress.setHorizontallyScrolling(false);
    }

    @Override
    protected void loadData() {
        preenter.getHMioMapData();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.tv_hmiomapcommit:
                scanResult = edtInputadress.getText().toString();

                if (TextUtils.isEmpty(scanResult)) {
                    showToast(getString(R.string.currency_hint1_inputadress));
                    break;
                }
                if (!EthWalletUtil.isETHValidAddress(scanResult)) {
                    showToast(getString(R.string.wallet_hint_warn));
                    break;
                }
                DialogUtils.enterPayPsw(this, (pwd1) -> {
                    preenter.getHmioBindData(scanResult, pwd1);
                });


                break;
            case R.id.tv_copyadress:
                copyWalletAddress(hMioMapDataDataData.getAddress());
                break;
            case R.id.tv_copymid:
                copyWalletAddress(hMioMapDataDataData.getSign());
                break;
            case R.id.img_saoma:
//                showToast("扫码");

                //扫码
                com.tbruyelle.rxpermissions2.RxPermissions rxPermissions = new com.tbruyelle.rxpermissions2.RxPermissions(HMioMapActivity.this);
                rxPermissions.request(Manifest.permission.CAMERA)
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Boolean granted) {
                                if (granted) {
                                    if (!CommonUtil.isCameraOpen()) {
                                        Intent intent = new Intent(HMioMapActivity.this, CaptureActivity.class);
                                        intent.putExtra(com.yzq.zxinglibrary.common.Constant.INTENT_ZXING_CONFIG, MyApp.getZxingConfig());
                                        startActivityForResult(intent, QRCODE_SCANNER_REQUEST);
                                    } else {
                                        showToast(getString(R.string.profile_hint_item1));
                                    }
                                } else {
                                    Toast.makeText(HMioMapActivity.this, getString(R.string.profile_hint_item2), Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });

                break;

        }
    }


    @Override
    public void getData(HMioMapData hMioMapData) {
        if (hMioMapData.getStatus() == 0) {

            hMioMapDataData = hMioMapData.getData();
            if (EmptyUtils.isNotEmpty(hMioMapDataData)) {
                /**
                 * bind_address : false
                 */
                tvMsg.setText(hMioMapDataData.getMsg());
                tvHmioMoney.setText(CommonUtil.saveToPoint4WithNo(hMioMapDataData.getHmio_money()));
                GlideApp.with(this)
                        .load(hMioMapDataData.getHmio_logo())
                        .error(R.drawable.icon_arctic)
                        .into(imgBizhongicon);

                if (hMioMapDataData.isBind_address()) {
                    //需要绑定
                    lyMidbody.setVisibility(View.GONE);
                    imgSaoma.setVisibility(View.VISIBLE);
                    tvCopyadress.setVisibility(View.GONE);
                    tvHmiomapcommit.setVisibility(View.VISIBLE);
                    tvHmiomapcommit.setOnClickListener(this);
                    imgSaoma.setOnClickListener(this);
                    tvCopyadress.setOnClickListener(null);
                    tvCopymid.setOnClickListener(null);

                } else {
                    imgSaoma.setVisibility(View.GONE);
                    tvCopyadress.setVisibility(View.VISIBLE);
//                    lyMidbody.setVisibility(View.VISIBLE);
                    lyMidbody.setVisibility(View.GONE);
                    tvHmiomapcommit.setVisibility(View.GONE);
                    tvHmiomapcommit.setOnClickListener(null);
                    imgSaoma.setOnClickListener(null);
                    tvCopyadress.setOnClickListener(this);
                }

                /**
                 * id : 1
                 * userId : 1
                 * sign : xzc
                 * address : asdsad
                 * createTime : 1577270335000
                 * status : 0
                 */
                hMioMapDataDataData = hMioMapDataData.getData();
                if (EmptyUtils.isNotEmpty(hMioMapDataDataData)) {

                    edtInputadress.setText(hMioMapDataDataData.getAddress());
                    edtInputadress.setFocusable(false);
                    edtInputadress.setFocusableInTouchMode(false);

                    if (EmptyUtils.isNotEmpty(hMioMapDataDataData.getSign())) {
                        tvHmiomid.setText(hMioMapDataDataData.getSign());
                        tvCopymid.setOnClickListener(this);
                    }

                }

            }

        } else {
            showToast(hMioMapData.getMsg());
        }
    }

    @Override
    public void getBuyHMioAddOrder(BuyHMioAddData registerData) {
        if (registerData.getStatus() == 0) {
            loadData();
        } else {
            showToast(registerData.getMsg());
        }
    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    String scanResult = "";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == QRCODE_SCANNER_REQUEST && resultCode == RESULT_OK && data != null) {
            String result = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT);
//            String result = null;
                    Log.i("TAG", "扫描结果:" + result);
            if (!TextUtils.isEmpty(result)) {
//                if ((tvBizhongtv.getText().toString().indexOf("ETH") != -1 && EthWalletUtil.isETHValidAddress(result)) || tvBizhongtv.getText().toString().indexOf("ETH") == -1) {
                //ethereum:0x3a6211d8A8d2B6375815E6d00421456554Bd0011?decimal=18&value=0
                scanResult = result;
                edtInputadress.setText(result.isEmpty() ? "" : result);
                if (scanResult.contains("ethereum")) {
                    scanResult = scanResult.replace("ethereum:", "").split("\\?")[0];
                    edtInputadress.setText(scanResult);
                }
            } else {
                Toast.makeText(HMioMapActivity.this, getString(R.string.profile_hint_item3), Toast.LENGTH_SHORT).show();
            }

        } else {
//            Toast.makeText(TurnOutActivity.this, getString(R.string.profile_hint_item4), Toast.LENGTH_SHORT).show();
//                AppUI.success(getContext(), "解析二维码失败");
        }
    }

    private void copyWalletAddress(String strs) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        if (cm != null) {
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", strs);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
        showToast(getString(R.string.profile_hint_item14));
//        tvCopyadress.setText(getString(R.string.profile_hint_item14));
    }
}
